import * as commonConst from "./commonConst";
import axios from "axios";
import { checkNullString } from "./mUtils";
/*
export default async (url = "", data = {}, type = "GET", method = "fetch") => {
  type = type.toUpperCase();
  url = commonConst.baseUrl + url;
  console.log(url);
  //console.log("请求data",data);
  if (type == "GET") {
    let dataStr = ""; //数据拼接字符串

    //防止缓存,令url每次不一样
    data["ttt"] = new Date().getTime();

    Object.keys(data).forEach(key => {
      dataStr += key + "=" + data[key] + "&";
    });

    if (dataStr !== "") {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf("&"));
      url = url + "?" + dataStr;
    }
  }

  if (window.fetch && method == "fetch") {
    // 		credentials项，其有3个值：
    // omit: 默认值，忽略cookie的发送
    // same-origin: 表示cookie只能同域发送，不能跨域发送
    // include: cookie既可以同域发送，也可以跨域发送
    //debugger;
    let requestConfig = {
      credentials: "omit", //如果跨域时候后台Access-Control-Allow-Origin设置为*,这里就不能写include, 也就是忽略发送cookies
      method: type,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      mode: "cors",
      cache: "force-cache"
    };

    if (type == "POST") {
      Object.defineProperty(requestConfig, "body", {
        //value: JSON.stringify(data)
        value: data
      });
    }

    try {
      const response = await fetch(url, requestConfig);
      const responseJson = await response.json();
      return responseJson;
    } catch (error) {
      throw new Error(error);
    }
  } else {
    return new Promise((resolve, reject) => {
      let requestObj;
      if (window.XMLHttpRequest) {
        requestObj = new XMLHttpRequest();
      } else {
        requestObj = new ActiveXObject();
      }

      let sendData = "";
      if (type == "POST") {
        sendData = JSON.stringify(data);
      }

      requestObj.open(type, url, true);
      // requestObj.setRequestHeader(
      //   "Content-type",
      //   "application/x-www-form-urlencoded"
      // );
      requestObj.setRequestHeader("Accept", "application/json");
      requestObj.setRequestHeader("Content-type", "application/json");
      requestObj.send(sendData);

      requestObj.onreadystatechange = () => {
        if (requestObj.readyState == 4) {
          if (requestObj.status == 200) {
            let obj = requestObj.response;
            if (typeof obj !== "object") {
              obj = JSON.parse(obj);
            }
            resolve(obj);
          } else {
            reject(requestObj);
          }
        }
      };
    });
  }
};
*/

export default async (
  url = "",
  data = {},
  type = "GET",
  needEditUser = true
) => {
  type = type.toUpperCase();
  url = commonConst.baseUrl + url;

  if (type == "GET") {
    // const paramdata = Object.assign({}, data, {
    //   ttt: new Date().getTime()
    // });

    let dataStr = ""; //数据拼接字符串

    //防止缓存,令url每次不一样
    data["ttt"] = new Date().getTime();

    Object.keys(data).forEach(key => {
      dataStr += key + "=" + data[key] + "&";
    });

    if (dataStr !== "") {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf("&"));
      url = url + "?" + dataStr;
    }

    try {
      const response = await axios.get(url);

      return response.data;
    } catch (error) {
      throw new Error(error);
    }
  }
  // POST
  else {
    try {
      //JSON.stringify(data)

      //post 加上用户名
      if (needEditUser) {
        let editUser = localStorage.getItem(commonConst.userNameKey);
        editUser = checkNullString(editUser);
        data.editUser = editUser;
        //console.log(" data.editUser:", data.editUser);
      }

      const response = await axios.post(url, data, {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        }
      });

      return response.data;
    } catch (error) {
      throw new Error(error);
    }
  }
};
